﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    [JwtAuthentication]
    public class ColaProductionFullInspectionRecordController : ApiController
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] ColaProductionFullInspectionRecord CPFIR)
        {
            ReturnObject RO = new ReturnObject();
            if (CPFIR == null ||
                string.IsNullOrEmpty(CPFIR.CPFIR_LineParting) ||
                string.IsNullOrEmpty(CPFIR.CPFIR_ProductionModel) ||
                string.IsNullOrEmpty(CPFIR.CPFIR_OrderNumber))
            {
                Logger.Warn("输入值无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "输入值无效";
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        var query = @"INSERT INTO ColaProductionFullInspectionRecord 
                                    (CPFIRProductionDate, CPFIRLineParting, CPFIRProductionModel, CPFIROrderNumber, 
                                     CPFIRProductionQuantity, CPFIRDefectiveQuantity, CPFIRBrokenFoot, CPFIRMixedMaterials, 
                                     CPFIRLaserMarkingDefect, CPFIRMissingGasket, CPFIRPoorHandfeel, CPFIRFinishedProductAppearance, 
                                     CPFIRMaterialAppearanceDefect, CPFIRSprayPaintAppearanceDefect, CPFIRDisconnectionDefect, 
                                     CPFIRPackagingDefect, CPFIRAssemblyDefect, CPFIRProtectiveDoorNotRebound, 
                                     CPFIRPlugNotFullyInserted, CPFIRVoltageResistanceDefect, CPFIRMarkingMismatch,CPFIRCreateCreator,CPFIRCreateTime)
                                    VALUES 
                                    (@ProductionDate, @LineParting, @ProductionModel, @OrderNumber, 
                                     @ProductionQuantity, @DefectiveQuantity, @BrokenFoot, @MixedMaterials, 
                                     @LaserMarkingDefect, @MissingGasket, @PoorHandfeel, @FinishedProductAppearance, 
                                     @MaterialAppearanceDefect, @SprayPaintAppearanceDefect, @DisconnectionDefect, 
                                     @PackagingDefect, @AssemblyDefect, @ProtectiveDoorNotRebound, 
                                     @PlugNotFullyInserted, @VoltageResistanceDefect, @MarkingMismatch,@CreateCreator,@CreateTime);
                                    SELECT CAST(scope_identity() AS int);";

                        SqlParameter[] parameters = {
                            new SqlParameter("@ProductionDate", SqlDbType.DateTime) { Value = CPFIR.CPFIR_ProductionDate },
                            new SqlParameter("@LineParting", SqlDbType.NVarChar, 50) { Value = CPFIR.CPFIR_LineParting },
                            new SqlParameter("@ProductionModel", SqlDbType.NVarChar, 50) { Value = CPFIR.CPFIR_ProductionModel },
                            new SqlParameter("@OrderNumber", SqlDbType.NVarChar, 50) { Value = CPFIR.CPFIR_OrderNumber },
                            new SqlParameter("@ProductionQuantity", SqlDbType.Int) { Value = CPFIR.CPFIR_ProductionQuantity },
                            new SqlParameter("@DefectiveQuantity", SqlDbType.Int) { Value = CPFIR.CPFIR_DefectiveQuantity },
                            new SqlParameter("@BrokenFoot", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_BrokenFoot ?? DBNull.Value },
                            new SqlParameter("@MixedMaterials", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_MixedMaterials ?? DBNull.Value },
                            new SqlParameter("@LaserMarkingDefect", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_LaserMarkingDefect ?? DBNull.Value },
                            new SqlParameter("@MissingGasket", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_MissingGasket ?? DBNull.Value },
                            new SqlParameter("@PoorHandfeel", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_PoorHandfeel ?? DBNull.Value },
                            new SqlParameter("@FinishedProductAppearance", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_FinishedProductAppearance ?? DBNull.Value },
                            new SqlParameter("@MaterialAppearanceDefect", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_MaterialAppearanceDefect ?? DBNull.Value },
                            new SqlParameter("@SprayPaintAppearanceDefect", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_SprayPaintAppearanceDefect ?? DBNull.Value },
                            new SqlParameter("@DisconnectionDefect", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_DisconnectionDefect ?? DBNull.Value },
                            new SqlParameter("@PackagingDefect", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_PackagingDefect ?? DBNull.Value },
                            new SqlParameter("@AssemblyDefect", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_AssemblyDefect ?? DBNull.Value },
                            new SqlParameter("@ProtectiveDoorNotRebound", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_ProtectiveDoorNotRebound ?? DBNull.Value },
                            new SqlParameter("@PlugNotFullyInserted", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_PlugNotFullyInserted ?? DBNull.Value },
                            new SqlParameter("@VoltageResistanceDefect", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_VoltageResistanceDefect ?? DBNull.Value },
                            new SqlParameter("@MarkingMismatch", SqlDbType.NVarChar, 500) { Value = (object)CPFIR.CPFIR_MarkingMismatch ?? DBNull.Value },
                            new SqlParameter("@CreateCreator", SqlDbType.NVarChar, 50) { Value = CPFIR.CPFIR_CreateCreator },
                            new SqlParameter("@CreateTime", SqlDbType.DateTime) { Value = DateTime.Now }
                        };

                        using (var command = new SqlCommand(query, connection, transaction))
                        {
                            command.Parameters.AddRange(parameters);
                            var result = await command.ExecuteScalarAsync();
                            if (result != null)
                            {
                                transaction.Commit();
                                CPFIR.CPFIR_ID = Convert.ToInt32(result);
                                Logger.Info("新增成功");
                                RO.Status = HttpStatusCode.OK;
                                RO.Message = "OK";
                                RO.Data = CPFIR;
                                return Request.CreateResponse(HttpStatusCode.OK, RO);
                            }
                            else
                            {
                                transaction.Rollback();
                                Logger.Error("插入记录失败");
                                RO.Status = HttpStatusCode.InternalServerError;
                                RO.Message = "Error";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Logger.Warn("新增失败: " + ex.Message);
                        RO.Status = HttpStatusCode.InternalServerError;
                        RO.Message = "Error" + ex.Message;
                        RO.Data = null;
                        return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                    }
                }
            }
        }
    }
}